import requests
from datetime import datetime, timedelta
import os, json
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

def fetch_data(url):
    rst = []
    response = requests.get(url)
    if response.status_code == 200:
        rst = response.json()
    else: #可能504错误，代理超时
        print(f"Error fetching data, error code  {response.status_code}")
    return rst

def getDateStr(dateStr):
    
    startDate = datetime.strptime(dateStr, "%Y-%m-%d")
    startDateStr = startDate.strftime("%Y-%m-%dT00:00:00Z")
    endDateStr = (startDate + timedelta(days=1)).strftime("%Y-%m-%dT00:00:00Z")
    
    return startDateStr, endDateStr

def getGWACSkyListByDate(saveDir, dateStr=""):
    
    gwac_url = "http://10.0.10.236/gwacWebHost/obsSky/obsSkyNumByMinutes"
    if len(dateStr) > 0:
        startDateStr, endDateStr = getDateStr(dateStr)
        #查询历史数据需要再GWAC圆顶服务器，这里直接使用内部地址
        gwac_url = f"http://172.28.8.8:3030/obsSky/obsSkyNumByMinutesHis?startDate={startDateStr}&endDate={endDateStr}"
    
    gwac_data_file = f"{saveDir}/gwac_data.json"
    if not os.path.exists(gwac_data_file):
        print('fetching data from GWAC...')
        gwac_data = fetch_data(gwac_url)
        with open(gwac_data_file, "w") as f:
            json.dump(gwac_data, f, indent=4)
    else:
        with open(gwac_data_file, "r") as f:
            gwac_data = json.load(f)
            
    return gwac_data

if __name__ == "__main__":
    
   getGWACSkyListByDate()